#!/bin/bash
set -e
PATH=$PATH:/usr/lib/jvm/default-jvm/bin/
export PATH

params=""

if [ ! -z "$MYSQL_HOST" ]; then
	params="$params --resource.mysql.host=$MYSQL_HOST"
fi

if [ ! -z "$MYSQL_PORT" ]; then
	params="$params --resource.mysql.port=$MYSQL_PORT"
fi

if [ ! -z "$MYSQL_USERNAME" ]; then
	params="$params --resource.mysql.username=$MYSQL_USERNAME"
fi

if [ ! -z "$MYSQL_PASSWORD" ]; then
	params="$params --resource.mysql.password=$MYSQL_PASSWORD"
fi

if [ ! -z "$REDIS_HOST" ]; then
	params="$params --resource.redis.host=$REDIS_HOST"
fi

if [ ! -z "$REDIS_PORT" ]; then
	params="$params --resource.redis.port=$REDIS_PORT"
fi

if [ ! -z "$REDIS_PASSWORD" ]; then
	params="$params --resource.redis.password=$REDIS_PASSWORD"
fi

if [[ ! -z "$INFLUXDB_HOST" && ! -z "$INFLUXDB_PORT" ]]; then
        params="$params --resource.influxdb.host=$INFLUXDB_HOST"
        params="$params --resource.influxdb.port=$INFLUXDB_PORT"
        params="$params --spring.influxdb.url=http://$INFLUXDB_HOST:$INFLUXDB_PORT"
fi

if [ ! -z "$INFLUXDB_USERNAME" ]; then
        params="$params --resource.influxdb.user=$INFLUXDB_USERNAME"
fi

if [ ! -z "$INFLUXDB_PASSWORD" ]; then
        params="$params --resource.influxdb.password=$INFLUXDB_PASSWORD"
fi

if [ ! -z "$WHITELISTPATH" ]; then
	params="$params --spring.config.whiteListPath=$WHITELISTPATH"
fi

if [ ! -z "$TRO_WEB_HOST" ]; then
	params="$params --takin-web.out.url=$TRO_WEB_HOST"
fi

if [ ! -z "$TRO_CLOUD_HOST" ]; then
	params="$params --takin-cloud.out.url=$TRO_CLOUD_HOST"
fi

if [ ! -z "$AMDB_HOST" ]; then
	params="$params --amdb.out.url=$AMDB_HOST"
fi

if [ ! -z "$ZK_HOSTS" ]; then
	params="$params --takin.config.zk.url=$ZK_HOSTS"
	params="$params --takin.pradar.zk.server=$ZK_HOSTS"
fi

/wait-for.sh $MYSQL_HOST:$MYSQL_PORT -t 60
/wait-for.sh $REDIS_HOST:$REDIS_PORT -t 60
/wait-for.sh $INFLUXDB_HOST:$INFLUXDB_PORT -t 60

cd /data/apps/takin-web
mkdir -p ./BOOT-INF/classes
envsubst < application-local.yml > ./BOOT-INF/classes/application-local.yml
cat ./BOOT-INF/classes/application-local.yml
jar -uvf takin-web-app.jar BOOT-INF/classes/application-local.yml

# java -Xms512m -Xmx512m -Xss1m  -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGCDateStamps -XX:+PrintGCDetails -Xloggc:/var/log/takin-web-gc.log  $DEBUG -jar /data/apps/takin-web/takin-web-app.jar $params
java -XX:MaxRAMPercentage=90.0 -Xmx$MEMORY -Xms$MEMORY -Xss1m -jar /data/apps/takin-web/takin-web-app.jar --spring.profiles.active=local